package io.summer.demo.examples;


import org.springframework.cglib.proxy.CallbackHelper;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.FixedValue;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.NoOp;

import java.lang.reflect.Method;

//cglib 除代理接口外，还可以代理类
public class CglibProxy {
  static class Hello {
    public void sayHello() {
      System.out.println("hello world");
    }

    public void bye() {
      System.out.println("bye!");
    }
  }

  static class TestFixValue extends Enhancer {
    TestFixValue() {
      setSuperclass(Hello.class);
      setCallback(new FixedValue() {
        @Override
        public Object loadObject() throws Exception {
          return "hello cglib";
        }
      });
    }
  }

  static class TestInterceptor extends Enhancer {
    TestInterceptor() {
      setSuperclass(Hello.class);
      CallbackHelper callbackHelper = new CallbackHelper(Hello.class, new Class[0]) {
        @Override
        protected Object getCallback(Method method) {
          if (method.getName().equals("bye")) {
            return (MethodInterceptor) (o, method1, objects, methodProxy) -> {
              System.out.println("MethodInterceptor: " + method1.getName());
              return methodProxy.invokeSuper(o, objects);
            };
          } else {
            return NoOp.INSTANCE;
          }
        }
      };
      setCallbackFilter(callbackHelper);
      setCallbacks(callbackHelper.getCallbacks());
    }
  }

  public static void main(String[] args) {
    Hello hello = (Hello) new TestFixValue().create();
    hello.bye();
    hello.sayHello();
    System.out.println(hello.toString());

    hello = (Hello) new TestInterceptor().create();
    hello.bye();
    hello.sayHello();
    System.out.println(hello.toString());
  }
}
